package org.esjsoftware.v2m.rim.audio.amrtowav;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 
 * @author Ermest
 *
 */
public class AmrToWav {
	public static ByteArrayOutputStream converAudioFiles(ByteArrayOutputStream baos) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		try {
			InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
			InputStream is = new ByteArrayInputStream(baos.toByteArray());
			byte[] buf = new byte[1024 * 4];
			int size = inputStream.read(buf);
			int PCMSize = 0;
			while (size != -1) {
				PCMSize += size;
				size = inputStream.read(buf);
			}
			inputStream.close();

			WaveHeader header = new WaveHeader();
			header.fileLength = PCMSize + (44 - 8);
			header.FmtHdrLeth = 16;
			header.BitsPerSample = 16;
			header.Channels = 1;
			header.FormatTag = 0x0001;
			header.SamplesPerSec = 8000;
			header.BlockAlign = (short) (header.Channels * header.BitsPerSample / 8);
			header.AvgBytesPerSec = header.BlockAlign * header.SamplesPerSec;
			header.DataHdrLeth = PCMSize;

			byte[] h = header.getHeader();

			// assert h.length == 44; 
			// write header
			outputStream.write(h, 0, h.length);
			
			// write data stream
			size = is.read(buf);
			while (size != -1) {
				outputStream.write(buf, 0, size);
				size = is.read(buf);
			}
			is.close();
			outputStream.close();			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		;
		return outputStream;
	}
}
